<template>
    <div>
        <div class="title">编辑账号</div>
        <el-form :model="form" label-width="120px" ref="ruleFormRef" :rules="rules" style="width: 500px;" status-icon>
            <el-form-item label="联系人" prop="real_name">
                <el-input v-model="form.real_name" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phone">
                <el-input v-model="form.phone" />
            </el-form-item>
            <el-form-item label="设置账号" prop="username">
                <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="设置密码" prop="password">
                <el-input v-model="form.password" show-password />
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="form.remark" />
            </el-form-item>
            <el-form-item v-if="route.query.id">
                <el-button @click="toHome">取消</el-button>
                <el-button type="primary" @click="editSubmit(ruleFormRef)">提交</el-button>
            </el-form-item>
            <el-form-item v-else="route.query.id">
                <el-button @click="Back">上一步</el-button>
                <el-button type="primary" @click="Submit(ruleFormRef)">提交</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup lang='ts'>
import { onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { useAddDataStore } from '../../store/useAddDataStore'
import { addMerchant, addPolice, getUseDetails, setUserPolice, setUserDetails } from '../../api/index'
import type { FormInstance, } from 'element-plus'
import { ElMessage } from 'element-plus'
const formData = useAddDataStore()
const ruleFormRef = ref<FormInstance>()
const router = useRouter()
const route = useRoute()
const editData = ref<any>({})
interface RuleForm {
    real_name: string
    phone: string
    username: string
    password: string
    remark?: string
}

const form = ref<RuleForm>({
    real_name: '',
    phone: '',
    username: '',
    password: '',
    remark: '',
})

const rules = ref({
    real_name: [
        {
            required: true,
            message: '请输入联系人姓名',
            trigger: 'blur'
        },
    ],
    phone: [
        {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
        },
        { pattern: /^1[0-9]{10}$/, message: '手机号格式不正确', trigger: 'blur' },
    ],
    username: [
        {
            required: true,
            message: '请输入账号',
            trigger: 'blur'
        },
        { pattern: /^[^\u4e00-\u9fa5]+$/, message: '账号不能包含汉字', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '密码应为6~16位', trigger: 'blur' },
    ],
})
const Back = () => {
    formData.backFlag = true
    router.push('/aiconfig')
}
const Submit = async (formEl: any) => {
    if (!formEl) return

    await formEl.validate(async (valid: any, fields: any) => {
        let res = null
        if (valid) {
            if (formData.business) {
                delete formData.from.city;
                formData.from.contact = form.value
                formData.from.permission_codes = formData.permission_codes
                res = await addMerchant(formData.from)
            } else {
                console.log(formData.policeForm);
                formData.policeForm.contact = form.value
                formData.policeForm.permission_codes = formData.permission_codes
                console.log(formData.policeForm);
                res = await addPolice(formData.policeForm)
            }
            if (res?.data.code === 0) {
                router.push('/')
                ElMessage({
                    message: '提交成功',
                    showClose: true,
                    type: 'success',
                })
            } else {
                ElMessage.error(res.data.message)
            }
        } else {
            ElMessage.error('提交失败')
        }
    })
}
const editSubmit = async (formEl: any) => {
    if (!formEl) return
    await formEl.validate(async (valid: any, fields: any) => {
        if (valid) {
            if (route.query.id) {
                //判断编辑的是商户还是公安
                if (Number(route.query.category) === 0 || Number(route.query.category) === 2) {
                    editData.value.contact = form.value
                    let res = await setUserPolice(editData.value)
                    if (res.data.code === 0) {
                        ElMessage({
                            message: '修改成功',
                            type: 'success',
                        })
                        router.push('/')
                    } else {
                        ElMessage.error('提交失败')
                    }
                } else {
                    editData.value.contact = form.value
                    let res = await setUserDetails(editData.value)
                    if (res.data.code === 0) {
                        ElMessage({
                            message: '修改成功',
                            type: 'success',
                        })
                        router.push('/')
                    } else {
                        ElMessage.error('提交失败')
                    }
                }
            }
        } else {
            ElMessage.error('提交失败')
        }
    })


}
const toHome = () => {
    router.push("/")
}
onMounted(async () => {
    if (route.query.id) {
        let res = (await getUseDetails({ id: route.query.id })).data.data
        form.value = {
            real_name: res.Administrator.real_name,
            phone: res.Administrator.phone,
            username: res.Administrator.username,
            password: '',
            remark: res.Administrator.remark,
        }
        rules.value = {
            real_name: [
                {
                    required: true,
                    message: '请输入联系人姓名',
                    trigger: 'blur'
                },
            ],
            phone: [
                {
                    required: true,
                    message: '请输入手机号',
                    trigger: 'blur'
                },
                { pattern: /^1[0-9]{10}$/, message: '手机号格式不正确', trigger: 'blur' },
            ],
            username: [
                {
                    required: true,
                    message: '请输入账号',
                    trigger: 'blur'
                },
                { pattern: /^[^\u4e00-\u9fa5]+$/, message: '账号不能包含汉字', trigger: 'blur' },
            ],
            password: [
                { required: false, message: '请输入密码', trigger: 'blur' },
                { min: 6, max: 16, message: '密码应为6~16位', trigger: 'blur' },
            ],
        }

        if (Number(route.query.category) === 0 || Number(route.query.category) === 2) {
            editData.value = {
                region_code: res.region_code,
                category: res.category,
                id: Number(route.query.id),
                location: res.location,
                name: res.name,
                permission_codes: res.PermissionCodes,
                pid: res.pid,
                point: res.point,
                status: res.status,
                communities: res.communities,
                contact: {}
            }
        } else {
            editData.value = {
                category: res.category,
                community_id: res.community_id,
                contact: {},
                id: Number(route.query.id),
                location: res.location,
                name: res.name,
                permission_codes: res.PermissionCodes,
                pid: res.pid,
                point: res.point,
                status: res.status
            }
        }
    }
})
</script>
<style scoped lang='less'>
.title {
    height: 30px;
    line-height: 25px;
    border-bottom: 1px solid #ddd;
    margin-bottom: 10px;
}
</style>